package cn.com.nes.common.util;

import cn.com.nes.site.module.dao.BaseDaoImpl;
import cn.hutool.core.codec.Base64Encoder;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.aliyuncs.utils.StringUtils;
import org.apache.commons.collections.IteratorUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.*;

//import com.nes.callcenter.mapper.ctce.UserWxUsersMapper;

/**
 * @author wuzx
 * @date 2022-01-05
 */
@Component
public class WxUtils {
    @Autowired
    private BaseDaoImpl baseDao;

    private static WxUtils wxUtils;
    @PostConstruct
    public void init() {
        wxUtils = this;
        wxUtils.baseDao = this.baseDao;
    }

    /**
     * 小程序登录校验
     *
     * @param appid
     * @param secret
     * @param code
     * @return
     */
    public static Map<String, Object> jscode2session(String appid, String secret, String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
        String post = HttpUtils.sendPost(url, "");
        JSONObject jsonObject = (JSONObject) JSON.parse(post);
        Map<String, Object> map = JSONObject.parseObject(jsonObject.toJSONString(), Map.class);
        return map;
    }

    /**
     * 获取关注公众号用户信息
     *
     * @return
     */
    public static List getAllUserInfo() {
        String wxAddressToken = getToken();

        String post1 = HttpUtils.sendPost("https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + wxAddressToken, "");
        JSONObject jsonObject1 = (JSONObject) JSON.parse(post1);
        JSONObject data = (JSONObject) jsonObject1.get("data");
        JSONArray openid = (JSONArray) data.get("openid");
        Iterator<Object> iterator = openid.iterator();
        List<String> list = IteratorUtils.toList(iterator);
        return list;
    }

    /**
     * 根据openId获取公众号用户信息
     *
     * @param id
     * @return
     */
    public static Map<String, Object> getUserInfo(String id) {
        String wxAddressToken = getToken();

        String post = HttpUtils.sendPost("https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + wxAddressToken + "&openid=" + id + "&lang=zh_CN", "");
        JSONObject jsonObject = (JSONObject) JSON.parse(post);
        Map<String, Object> map = JSONObject.parseObject(jsonObject.toJSONString(), Map.class);
        return map;
    }

    /**
     * 根据openId列表获取公众号用户信息
     *
     * @param id
     * @return
     */
    public static List<Map<String, Object>> getUserInfo(List<String> id) {
        String wxAddressToken = getToken();
        Map map = new HashMap();
        List<Map<String, Object>> userInfos = new ArrayList<>();
        List<Map<String, Object>> list = new ArrayList<>();
        int count = 0;
        for (int i = 0; i < id.size(); i++) {
            if (count >= 100) {
                map.put("user_list", list);
                count = 0;
                list = new ArrayList<>();
                String post = HttpUtils.sendPost("https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token=" +
                        wxAddressToken, JSON.toJSONString(map));
                JSONObject jsonObject = (JSONObject) JSON.parse(post);
                JSONArray user_info_list = (JSONArray) jsonObject.get("user_info_list");
                if (user_info_list != null) {
                    Iterator<Object> iterator = user_info_list.iterator();
                    while (iterator.hasNext()) {
                        JSONObject next = (JSONObject) iterator.next();
                        Map<String, Object> map1 = new HashMap<>();
                        map1.put("openid", next.get("openid"));
                        map1.put("unionid", next.get("unionid"));
                        map1.put("subscribe", next.get("subscribe"));
                        userInfos.add(map1);
                    }
                }
                map = new HashMap();
            }
            Map<String, Object> map1 = new HashMap<>();
            map1.put("openid", id.get(i));
            map1.put("lang", "zh_CN");
            list.add(map1);
            count++;
        }
        if (count > 0) {
            map.put("user_list", list);
            count = 0;
            list = new ArrayList<>();
            String post = HttpUtils.sendPost("https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token=" +
                    wxAddressToken, JSON.toJSONString(map));
            JSONObject jsonObject = (JSONObject) JSON.parse(post);
            JSONArray user_info_list = (JSONArray) jsonObject.get("user_info_list");
            if (user_info_list != null) {
                Iterator<Object> iterator = user_info_list.iterator();
                while (iterator.hasNext()) {
                    JSONObject next = (JSONObject) iterator.next();
                    Map<String, Object> map1 = new HashMap<>();
                    map1.put("openid", next.get("openid"));
                    map1.put("unionid", next.get("unionid"));
                    map1.put("subscribe", next.get("subscribe"));
                    userInfos.add(map1);
                }
            }
            map = new HashMap();
        }
        return userInfos;
    }

    //发送通知
    public static String sendTempM(String openId, String accessToken, String gmtCreate, String info, String system, int isAleadySend) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("touser", openId);
        map.put("template_id", "fVuVgsoOhTMS2gtsBpH1vCnf39s8T_j4om62sgoy9Tk");//模板消息id

        String color = "#173177";
        if (isAleadySend == 0) {
            color = "#ff0000";
        }
        // 封装first
        Map firstMap = new HashMap();
        firstMap.put("value", "天气预警"); //内容
        firstMap.put("color", "#173177"); //字体颜色

        // 封装keyword1 提交的问题
        Map keyword1Map = new HashMap();
        keyword1Map.put("value", gmtCreate);
        keyword1Map.put("color", "#173177");

        // 封装keyword2此处也可以是商品名
        Map keyword2Map = new HashMap();
        keyword2Map.put("value", "降雪降温预警");
        keyword2Map.put("color", "#173177");

        // 封装keyword2此处可以是商品价格
        Map keyword3Map = new HashMap();
        keyword3Map.put("value", info);
        keyword3Map.put("color", color);

        Map remarkMap = new HashMap();
        remarkMap.put("value", null);
        remarkMap.put("color", color);

        // 封装data
        Map dataMap = new HashMap();
        dataMap.put("first", firstMap);
        dataMap.put("keyword1", keyword1Map);
        dataMap.put("keyword2", keyword2Map);
        dataMap.put("keyword3", keyword3Map);
        dataMap.put("remark", remarkMap);

        map.put("data", dataMap);


//        String r = getJsonData(JSONObject.parseObject(JSON.toJSONString(map)), "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken); //发送模板消息，这里有个工具类，我给你哟
        String r = HttpUtils.sendPost("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken, JSON.toJSONString(map));
        if (!StringUtils.isEmpty(r)) {
            JSONObject jsonObject = JSONObject.parseObject(r);
            String errcode = String.valueOf(jsonObject.getString("errcode"));
            if ("0".equals(errcode)) {
                r = "OK";
            }
        } else {

        }

        return r;
    }

    public static String getToken() {
        StringBuffer sb = new StringBuffer();
        PreparedStatement ps = null;
        ResultSet rs = null;
        Connection ctce_conn = null;
        String token = null;
        try {
            ctce_conn = null;//wxUtils.baseDao.getDBConnect_ctce();

            sb.delete(0, sb.length());
            sb.append(" SELECT csz from t_xtcs where csm='accessToken' ");
            ps = ctce_conn
                    .prepareStatement(sb.toString(),
                            ResultSet.TYPE_SCROLL_SENSITIVE,
                            ResultSet.CONCUR_READ_ONLY);
            rs = ps.executeQuery();
            if (rs.next()) {
                token = rs.getString("csz");
            }
            rs.close();
            ps.close();


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (ps != null) {
                    ps.close();
                }
                if (ctce_conn != null) {
                    ctce_conn.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return token;
    }
    
    
    
    /**
     * 通过图片的url获取图片的base64字符串
     * @param imgUrl    图片url
     * @return    返回图片base64的字符串
     */
    public static String image2Base64(String imgUrl) {
        URL url = null;
        InputStream is = null;
        ByteArrayOutputStream outStream = null;
        HttpURLConnection httpUrl = null;
        try {
            url = new URL(imgUrl);
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            httpUrl.getInputStream();
            is = httpUrl.getInputStream();
            outStream = new ByteArrayOutputStream();
            //创建一个Buffer字符串
            byte[] buffer = new byte[1024];
            //每次读取的字符串长度，如果为-1，代表全部读取完毕
            int len = 0;
            //使用一个输入流从buffer里把数据读取出来
            while ((len = is.read(buffer)) != -1) {
                //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
                outStream.write(buffer, 0, len);
            }
            // 对字节数组Base64编码
            Base64Encoder base64Encoder  = new Base64Encoder();
            return base64Encoder.encode(outStream.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outStream != null) {
                try {
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpUrl != null) {
                httpUrl.disconnect();
            }
        }
        return imgUrl;
    }
}
